// wiki: https://banchengyun.w.eolinker.com/share/project/api/?groupID=-1&shareCode=5FgX6i&shareToken=$2y$10$OQeOHjW6vTS9tLo2ZYAE5erqmd4Xzo27bIWj9M1hVRtQOjTgbgqvW&shareID=322316
import { http, getDocuments, createDocument, getCurrentDate, stringToDate, clearDocuments } from '../index.js';
/**
 * app 配置
*/
var APP_CONFIG = {
  'appid': 'bczzjh1lhpk2mhuq7b',
  'secret': 'rf9i4gyrsofi0wp3217d7ruxi6h0uj9u',
  'grant_type': 'client_credential'
}

/**
 * token uri
*/
var API_ORIGIN = 'https://open.banchengyun.com/api';

/**
 * 拼接 url
 * @param {string} path
*/
export function getURL(path) {
  return API_ORIGIN + path;
}

/**
 * 获取 access_token
*/
export function getToken() {
  var formName = 'token缓存';
  var tokenDocument = getDocuments({
    formName
  })
  // 如果缓存有token且未到期，从缓存取
  // token 有效期为7天，如果到期时间小于一天就重新获取
  if (tokenDocument.size() > 0) {
    var doc = tokenDocument.get(0);
    var token = doc.getElementByName('token').getValue();
    var expireAt = doc.getElementByName('过期时间').getValue();
    var expireAtTimestamp = stringToDate(expireAt, 'yyyy-MM-dd hh:ss').getTime();
    if (expireAtTimestamp - getCurrentDate().getTime() > 864e5) {
      return token;
    }
  }
  return requestToken();
}

/**
 * 请求 access_token
*/
export function requestToken() {
  var uri = getURL('/token');
  var params = APP_CONFIG;
  var formName = 'token缓存';
  var res = http.get({
    uri,
    params
  })
  // 获取超时重试
  if (res.code == 40000) {
    // 重试获取 token
    return requestToken();
  }
  // 清空token缓存表单
  clearDocuments(formName)
  var token = res.data.access_token;
  var expire = res.data.expired_at * 1000;
  // 插入到 token 缓存表
  createDocument({
    formName,
    formData: {
      token,
      '过期时间': expire
    }
  })
  return token;
}

export var $http = {
  get({ uri, params = {}, headers }) {
    return this.handle({
      method: 'get',
      uri,
      params,
      headers
    })
  },
  post({ uri, params = {}, headers, data }) {
    return this.handle({
      method: 'post',
      uri,
      params,
      headers,
      data
    })
  },
  handle({ method, uri, params, headers, data }) {
    var req = function() {
      params.access_token = getToken();
      return http[method]({
        uri,
        params,
        headers,
        data
      })
    }
    var res = req();
    // 如果token失效，重新获取 token
    if ([41000, 41001, 41004].indexOf(res.code) > -1) {
      // 清空token缓存表单
      clearDocuments('token缓存');
      res = req();
    }
    // 半城云接口有时候请求第一次报超时，需要重新请求
    // 如果请求超时，重新获取
    if (res.code == 40000) {
      res = req();
    }
    return res;
  }
}
